<template>
    <div class="stats-container">
        <div class="chart-container">
            <div class="controls-row">
                <div class="date-picker">
                    <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        :default-value="[new Date(new Date().setDate(new Date().getDate() - 7)), new Date()]"
                        @change="handleDateRangeChange" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                </div>

                <div class="stat-item">
                    <span class="stat-label">总销售额</span>
                    <span class="stat-value">{{ totalSales.toLocaleString() }} 元</span>
                </div>

                <div class="stat-item">
                    <span class="stat-label">总销售量</span>
                    <span class="stat-value">{{ totalVolume.toLocaleString() }} 件</span>
                </div>
                <div style="flex:1;"></div>

                <div class="sort-controls">
                    <button @click="sortData('sales', 'asc')"
                        :class="{ active: sortField === 'sales' && sortOrder === 'asc' }">销售额 ↑</button>
                    <button @click="sortData('sales', 'desc')"
                        :class="{ active: sortField === 'sales' && sortOrder === 'desc' }">销售额 ↓</button>
                    <button @click="sortData('volume', 'asc')"
                        :class="{ active: sortField === 'volume' && sortOrder === 'asc' }">销售量 ↑</button>
                    <button @click="sortData('volume', 'desc')"
                        :class="{ active: sortField === 'volume' && sortOrder === 'desc' }">销售量 ↓</button>
                </div>
            </div>
            <div ref="chartRef" class="chart-content"></div>
        </div>

        <div class="charts-row">
            <div class="chart-container half-width">
                <div class="controls-row">
                    <h3 class="chart-title">最近6个月销售趋势</h3>
                    <div class="trend-controls">
                        <el-date-picker v-model="trendDateRange" type="monthrange" range-separator="至"
                            start-placeholder="开始月份" end-placeholder="结束月份" :default-value="generateLast6MonthsRange()"
                            @change="updateTrendChart" format="YYYY-MM" value-format="YYYY-MM" />
                    </div>
                    <div class="trend-stats">
                        <div class="stat-item">
                            <span class="stat-label">期间销售总额</span>
                            <span class="stat-value">{{ trendTotalSales.toLocaleString() }} 元</span>
                        </div>
                        <div class="stat-item">
                            <span class="stat-label">期间销售总量</span>
                            <span class="stat-value">{{ trendTotalVolume.toLocaleString() }} 件</span>
                        </div>
                    </div>
                </div>
                <div ref="trendChartRef" class="chart-content" style="width: 100%; height: 600px;"></div>
            </div>

            <div class="chart-container half-width" style="margin-left: 20px;">
                <div class="controls-row">
                    <h3 class="chart-title">销售分布</h3>

                    <el-date-picker v-model="pieChartMonth" type="month" placeholder="选择月份" format="YYYY-MM"
                        value-format="YYYY-MM" @change="updatePieChart" :default-value="new Date()" />
                    <div style="flex:1"></div>

                    <div class="stat-item">
                        <div class="stat-label">月度销售额</div>
                        <div class="stat-value">{{ pieTotalSales.toLocaleString() }} 元</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-label">月度销售量</div>
                        <div class="stat-value">{{ pieTotalVolume.toLocaleString() }} 件</div>
                    </div>
                    
                    <button @click="switchPieData('sales')" style="margin-left: 10px;"
                        :class="{ active: pieDataType === 'sales' }">销售额</button>
                    <button @click="switchPieData('volume')" style="margin-left: 10px;"
                        :class="{ active: pieDataType === 'volume' }">销售量</button>


                </div>
                <div ref="pieChartRef" class="chart-content"></div>
            </div>
        </div>

    </div>
</template>

<script setup>
import { onMounted, ref, onBeforeUnmount, nextTick } from 'vue';
import * as echarts from 'echarts';
import { ElDatePicker } from 'element-plus';

const chartRef = ref(null);
let chartInstance = null;
const dateRange = ref([]);
const sortField = ref('sales');
const sortOrder = ref('desc');


// 处理日期范围变化
const handleDateRangeChange = (val) => {
    if (val) {
        updateChartData();
    }
};

// 生成模拟数据，按天存储
const generateDailyData = (date) => {
    return Array.from({ length: 100 }, (_, index) => ({
        name: `销售员${index + 1}`,
        sales: Math.floor(Math.random() * 5000) + 1000,
        volume: Math.floor(Math.random() * 50) + 10,
        date: date
    }));
};

// 存储销售数据
const salesDataMap = new Map();

// 初始化数据
const initializeSalesData = () => {
    if (!dateRange.value || dateRange.value.length !== 2) return;
    const [start, end] = dateRange.value;
    for (let date = new Date(start); date <= new Date(end); date.setDate(date.getDate() + 1)) {
        const dateStr = date.toISOString().split('T')[0];
        salesDataMap.set(dateStr, generateDailyData(dateStr));
    }
};

// 合并日期范围内的数据
const mergeDateRangeData = () => {
    if (!dateRange.value || dateRange.value.length !== 2) return [];
    const salesByPerson = new Map();
    const [start, end] = dateRange.value;

    for (let date = new Date(start); date <= new Date(end); date.setDate(date.getDate() + 1)) {
        const dateStr = date.toISOString().split('T')[0];
        const dailyData = salesDataMap.get(dateStr) || generateDailyData(dateStr);

        dailyData.forEach(person => {
            const existing = salesByPerson.get(person.name) || { name: person.name, sales: 0, volume: 0 };
            existing.sales += person.sales;
            existing.volume += person.volume;
            salesByPerson.set(person.name, existing);
        });
    }

    return Array.from(salesByPerson.values());
};

// 排序数据
const sortData = (field, order) => {
    sortField.value = field;
    sortOrder.value = order;
    updateChartData();
};

const tableData = ref([]);

const totalSales = ref(0);
const totalVolume = ref(0);

const updateChartData = () => {
    if (!chartInstance || !dateRange.value) return;

    const [start, end] = dateRange.value;
    initializeSalesData();
    let mergedData = mergeDateRangeData();

    // 计算总计
    totalSales.value = mergedData.reduce((sum, item) => sum + item.sales, 0);
    totalVolume.value = mergedData.reduce((sum, item) => sum + item.volume, 0);

    // 根据选择的字段和顺序进行排序
    mergedData = [...mergedData].sort((a, b) => {
        const multiplier = sortOrder.value === 'asc' ? 1 : -1;
        return (a[sortField.value] - b[sortField.value]) * multiplier;
    });

    // 更新表格数据
    tableData.value = mergedData;

    const option = {
        title: {
            text: `商城订单统计 (${dateRange.value[0]} 至 ${dateRange.value[1]})`,
            left: 'center'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        legend: {
            data: ['销售额', '销售量'],
            top: '10%',
            type: 'scroll',
            pageButtonPosition: 'end'
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true,
            height: '75%'
        },
        xAxis: {
            type: 'category',
            data: mergedData.map(item => item.name),
            axisLabel: {
                interval: 0,
                rotate: 45
            }
        },
        yAxis: [
            {
                type: 'value',
                name: '销售额',
                position: 'left',
                axisLabel: {
                    formatter: '{value} 元'
                }
            },
            {
                type: 'value',
                name: '销售量',
                position: 'right',
                axisLabel: {
                    formatter: '{value} 件'
                }
            }
        ],
        series: [
            {
                name: '销售额',
                type: 'bar',
                data: mergedData.map(item => item.sales),
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
                        { offset: 0, color: '#a8d8ff' },
                        { offset: 0.5, color: '#60abf8' },
                        { offset: 1, color: '#3492ed' }
                    ])
                },
                barWidth: '15%',
                barGap: '30%'
            },
            {
                name: '销售量',
                type: 'bar',
                yAxisIndex: 1,
                data: mergedData.map(item => item.volume),
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
                        { offset: 0, color: '#95e4b0' },
                        { offset: 0.5, color: '#5fc378' },
                        { offset: 1, color: '#39b356' }
                    ])
                },
                barWidth: '15%'
            }
        ],
        dataZoom: [
            {
                type: 'slider',
                xAxisIndex: 0,
                bottom: '2%',
                start: 0,
                end: 20
            },
            {
                type: 'inside',
                xAxisIndex: 0,
                start: 0,
                end: 20
            }
        ]
    };

    chartInstance.setOption(option);
    updatePieChart(); // 同步更新饼图数据
};

const trendChartRef = ref(null);
let trendChartInstance = null;
const trendDateRange = ref([]);
const trendTotalSales = ref(0);
const trendTotalVolume = ref(0);

// 生成最近6个月的日期范围
const generateLast6MonthsRange = () => {
    const end = new Date();
    const start = new Date();
    start.setMonth(start.getMonth() - 5);
    return [start.toISOString().slice(0, 7), end.toISOString().slice(0, 7)];
};

// 生成月度数据
const generateMonthlyData = () => {
    const monthlyData = new Map();
    const [start, end] = generateLast6MonthsRange();

    for (let date = new Date(start); date <= new Date(end); date.setMonth(date.getMonth() + 1)) {
        const monthKey = date.toISOString().slice(0, 7);
        const daysInMonth = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();

        const monthData = new Map();
        for (let day = 1; day <= daysInMonth; day++) {
            const currentDate = new Date(date.getFullYear(), date.getMonth(), day);
            const dateStr = currentDate.toISOString().split('T')[0];
            const dailyData = generateDailyData(dateStr);

            dailyData.forEach(person => {
                const existing = monthData.get(person.name) || { name: person.name, sales: 0, volume: 0 };
                existing.sales += person.sales;
                existing.volume += person.volume;
                monthData.set(person.name, existing);
            });
        }
        monthlyData.set(monthKey, Array.from(monthData.values()));
    }
    return monthlyData;
};

// 更新趋势图表
const updateTrendChart = () => {
    if (!trendChartInstance) return;
    console.log("updateTrendChart-1")
    const monthlyData = generateMonthlyData();
    console.log("Generated monthly data:", monthlyData);
    const months = Array.from(monthlyData.keys())
        .filter(month => {
            if (!trendDateRange.value || trendDateRange.value.length !== 2) return true;
            return month >= trendDateRange.value[0] && month <= trendDateRange.value[1];
        })
        .sort();

    // 计算每月的总销售额和总销售量
    const monthlyTotals = months.map(month => {
        const monthData = monthlyData.get(month);
        return {
            sales: monthData.reduce((sum, person) => sum + person.sales, 0),
            volume: monthData.reduce((sum, person) => sum + person.volume, 0)
        };
    });
    console.log("updateTrendChart-2")
    // 计算总计
    trendTotalSales.value = monthlyTotals.reduce((sum, total) => sum + total.sales, 0);
    trendTotalVolume.value = monthlyTotals.reduce((sum, total) => sum + total.volume, 0);

    const option = {
        title: {
            text: '最近6个月销售趋势',
            left: 'center'
        },
        tooltip: {
            trigger: 'axis',
            formatter: function (params) {
                let result = params[0].axisValue + '<br/>';
                params.forEach(param => {
                    const value = param.value.toLocaleString();
                    const unit = param.seriesName === '销售总额' ? ' 元' : ' 件';
                    result += param.marker + param.seriesName + ': ' + value + unit + '<br/>';
                });
                return result;
            }
        },
        legend: {
            data: ['销售总额', '销售总量'],
            bottom: 0
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '10%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: months.map(m => m.replace('-', '年') + '月'),
            axisLabel: {
                interval: 0
            }
        },
        yAxis: [
            {
                type: 'value',
                name: '销售总额',
                axisLabel: {
                    formatter: '{value} 元'
                }
            },
            {
                type: 'value',
                name: '销售总量',
                position: 'right',
                axisLabel: {
                    formatter: '{value} 件'
                }
            }
        ],
        series: [
            {
                name: '销售总额',
                type: 'line',
                data: monthlyTotals.map(total => total.sales),
                smooth: true,
                lineStyle: {
                    width: 3
                },
                itemStyle: {
                    color: '#3492ed'
                }
            },
            {
                name: '销售总量',
                type: 'line',
                yAxisIndex: 1,
                data: monthlyTotals.map(total => total.volume),
                smooth: true,
                lineStyle: {
                    width: 3
                },
                itemStyle: {
                    color: '#39b356'
                }
            }
        ]
    };

    trendChartInstance.setOption(option);
};

// 定义resize处理函数
const handleResize = () => {
    if (chartInstance) {
        chartInstance.resize();
    }
    if (trendChartInstance) {
        trendChartInstance.resize();
    }
    if (pieChartInstance) {
        pieChartInstance.resize();
    }
};

onMounted(() => {
    if (chartRef.value) {
        const chartContainer = chartRef.value;
        chartContainer.style.width = '100%';
        chartContainer.style.height = '700px';
        chartInstance = echarts.init(chartContainer);
        // 设置默认日期范围
        dateRange.value = [
            new Date().toISOString().split('T')[0],
            new Date().toISOString().split('T')[0]
        ];
        updateChartData();
    }

    if (trendChartRef.value) {
        const trendContainer = trendChartRef.value;
        trendContainer.style.width = '100%';
        trendContainer.style.height = '600px';
        trendChartInstance = echarts.init(trendContainer);
        // 设置默认趋势日期范围
        trendDateRange.value = generateLast6MonthsRange();
        // 确保DOM更新后再初始化图表
        nextTick(() => {
            updateTrendChart();
        });
    }

    if (pieChartRef.value) {
        const pieContainer = pieChartRef.value;
        pieContainer.style.width = '100%';
        pieContainer.style.height = '600px';
        pieChartInstance = echarts.init(pieContainer);
        updatePieChart();
    }

    // 统一添加resize事件监听
    window.addEventListener('resize', handleResize);
});

onBeforeUnmount(() => {
    if (chartInstance) {
        chartInstance.dispose();
        chartInstance = null;
    }
    if (trendChartInstance) {
        trendChartInstance.dispose();
        trendChartInstance = null;
    }
    window.removeEventListener('resize', handleResize);
});

const pieChartRef = ref(null);

const pieTotalSales=ref(0) 
const pieTotalVolume=ref(0)

let pieChartInstance = null;
const pieDataType = ref('sales');
const pieChartMonth = ref(new Date().toISOString().slice(0, 7));

// 切换饼图数据类型
const switchPieData = (type) => {
    pieDataType.value = type;
    updatePieChart();
};

// 更新饼图数据
const updatePieChart = () => {
    if (!pieChartInstance || !pieChartMonth.value) return;

    // 生成选中月份的数据
    const monthData = generateMonthlyData().get(pieChartMonth.value) || [];
    
    // 计算月度总销售额和总销售量
    pieTotalSales.value = monthData.reduce((sum, item) => sum + item.sales, 0);
    pieTotalVolume.value = monthData.reduce((sum, item) => sum + item.volume, 0);
//     const pieTotalSales=ref(0) 
// const pieTotalVolume=ref(0)
    const option = {
        title: {
            text: `${pieChartMonth.value.replace('-', '年')}月 - ${pieDataType.value === 'sales' ? '销售额' : '销售量'}分布`,
            left: 'center'
        },
        tooltip: {
            trigger: 'item',
            formatter: function (params) {
                const unit = pieDataType.value === 'sales' ? ' 元' : ' 件';
                return `${params.name}<br/>${params.value.toLocaleString()}${unit} (${params.percent}%)`;
            }
        },
        series: [
            {
                type: 'pie',
                radius: '65%',
                center: ['50%', '50%'],
                data: monthData.map(item => ({
                    name: item.name,
                    value: item[pieDataType.value]
                })),
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                },
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    formatter: '{b}: {d}%'
                }
            }
        ]
    };

    pieChartInstance.setOption(option);
};



onBeforeUnmount(() => {
    if (pieChartInstance) {
        pieChartInstance.dispose();
        pieChartInstance = null;
    }
});
</script>



<style lang="scss" scoped>
.stats-container {
    padding: 20px;
    height: 100vh;
    overflow-y: auto;
}

.data-table {
    margin-bottom: 20px;
    overflow-x: auto;

    table {
        width: 100%;
        border-collapse: collapse;
        margin-bottom: 1rem;
        background-color: white;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    }

    th,
    td {
        padding: 12px;
        text-align: left;
        border-bottom: 1px solid #eee;
    }

    th {
        background-color: #f8f9fa;
        font-weight: 600;

        &.sortable {
            cursor: pointer;
            user-select: none;

            &:hover {
                background-color: #e9ecef;
            }

            &.active {
                color: #188df0;
            }
        }
    }

    tr:hover {
        background-color: #f8f9fa;
    }

    td {
        font-size: 0.95rem;
    }
}

.controls-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 20px;
    background-color: white;
    padding: 0px 20px;
    height: 80px;
    z-index: 1;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
}

.stats-container {
    padding: 20px;
    height: 100vh;
    overflow-y: auto;
}

.date-picker {
    flex: 1;
    max-width: 400px;

    :deep(.el-date-picker) {
        width: 100%;
    }
}

.sort-controls {
    display: flex;
    gap: 5px;
    flex-wrap: wrap;

    button {
        margin: 0 5px;
        padding: 8px 16px;
        border: 1px solid #ddd;
        border-radius: 4px;
        background-color: white;
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover {
            background-color: #f5f5f5;
        }

        &.active {
            background-color: #188df0;
            color: white;
            border-color: #188df0;
        }
    }
}

.charts-row {
    display: flex;
}

.chart-container {
    width: 100%;
    height: 800px;
    margin: 20px 0;
    padding: 0;
    background-color: white;
    // background-color: #c9c9c9;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    display: block;

    .chart-content {
        width: 100%;
        height: 600px;
        padding: 0;
        box-sizing: border-box;
    }
}

.chart-title {
    margin: 0;
    font-size: 1.2em;
    color: #333;
}

.trend-controls {
    flex: 1;
    max-width: 400px;
    margin: 0 20px;
}

.trend-stats {
    display: flex;
    gap: 20px;

    .stat-item {
        display: flex;
        flex-direction: column;
        align-items: flex-start;

        .stat-label {
            font-size: 14px;
            color: #666;
        }

        .stat-value {
            font-size: 18px;
            font-weight: 600;
            color: #333;
        }
    }
}
</style>
